26
Beginner’s Guide to Code Algorithms
26
Function NextEmptyFormCell(ByRef EmptyX, EmptyY, OScore, XScore)
Dim Factor(3)
Factor(1) = Array(0, 2, 3, 5)
Factor(2) = Array(0, 7, 11, 13)
Factor(3) = Array(0, 17, 19, 23)
OScore = 1
XScore = 1
EmptyCount = 0
EmptyX = 0
EmptyY = 0
For i = 1 To 3
For j = 1 To 3
If UserForm1.Controls("TextBox" & (i - 1) * 3 + j) = "" Then
EmptyCount = EmptyCount + 1
EmptyX = i
EmptyY = j
Else
If UserForm1.Controls("TextBox" & (i - 1) * 3 + j) = "X" Then
XScore = XScore * Factor(i)(j)
Else
OScore = OScore * Factor(i)(j)
End If
End If
Next j
Next i
NextEmptyFormCell = EmptyCount
End Function
FIGURE 2.24 Find Next Empty Cell.
Here is how the computer determines the best move:
First, the computer examines if the next move by itself will result in a win.
Second, the computer considers that if it cannot win, can it prevent its opponent from
winning? if the next move by the opponent will result in a win, it tries to block it by
placing a “O”.
Third, if neither of these are possible, then it determines the best cell.
All the three steps are based upon the algorithmic score described in the next
section.
WinTag(k) stores the winning scores that are compared to the score attained by
filling in that cell. The Greatest Common Divisor (GCD) function returns the cell’s
assigned value if the cell is a winning cell. In Step 3, the GCD is greater than 1 if the
cell value is a multiple of any of the eight WinTag(k) scores. A count is kept of how
many scores the value of the cell is a multiple of. The higher the number, the better
the choice of the cell.